package com.top.art.tool;

import com.alibaba.fastjson.JSON;
import com.top.art.vo.AccountInfoVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

/**
 * The type Jwt token.
 *
 * @author hjh
 */
@Component
public class JwtToken {
    private final static Long EXPIRE = 1000 * 60 * 60 * 24L;

    private final static Key KEY = Keys.hmacShaKeyFor("top美术培训,国庆无聊兼职七天。。。".getBytes(StandardCharsets.UTF_8));

    private final static String SALT = "国庆兼职";

    /**
     * Generate token string.
     *
     * @param accountInfo the account info
     * @return the string
     */
    public String generateToken(AccountInfoVO accountInfo) {
        return Jwts.builder()
                .claim("salt", SALT)
                .claim("userinfo", JSON.toJSONString(accountInfo))
                .setSubject(accountInfo.getAccount())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(KEY).compact();
    }

    /**
     * Parse token claims.
     *
     * @param token the token
     * @return the claims
     */
    public Claims parseToken(String token) {
        return Jwts.parser().require("salt", SALT)
                .setSigningKey(KEY).parseClaimsJws(token).getBody();
    }

    /**
     * Parse account string.
     *
     * @param token the token
     * @return the string
     */
    public String parseAccount(String token) {
        return parseToken(token).getSubject();
    }
}
